var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var redis = require('socket.io-redis');
io.adapter(redis({ host: 'localhost', port: 6379 }));
const user = require("./user.js");
const room = require("./room.js");
//var Redis = require('ioredis');
//var red = new Redis(6379);

//var G = require("./game.js");

app.get('/', function(req, res){
  	res.sendFile(__dirname + '/testSocket.html');
});

let mysql_config = {
    db_type: 'mysql', // 数据库类型,支持mysql,postgressql,sqlite3
    db_host: '127.0.0.1', // 服务器地址
    db_port: 3306, // 端口
    db_name: 'game', // 数据库名
    db_user: 'huanghe', // 用户名
    db_pwd: '111111', // 密码
};

let userModel = new user(mysql_config);

let game = {};//房间数据

let links = {};//所有连接者

let clock = {};//所有时钟

let roomModel = new room(mysql_config);

//删除数据库
roomModel.query("truncate table rooms");

io.on("connection",socket=>{
	links[socket.id] = socket;
	//socket.room_id = false;
	//links[socket.id].room_id = false;

	//监听有人进入
	socket.on("root_room",msg=>{
		let userInfo = JSON.parse(msg);
		//roomModel = new room(mysql_config);
    	if(userInfo.type[0] == "fast"){
    		//快速开始游戏
    		//寻找一个房间,如果没有可用的房间就创建一个房间
    		async function go_to_fast(){
    			let rooms = await roomModel.where({is_valid:{'>':0},user_num:{">":0,"<":10}}).find();
    			if(isEmpty(rooms)){
    				let rid = await roomModel.add({start_time:time(),is_valid:1,user_num:1});
    				return await roomModel.where({id:rid}).find();
    			}else{
    				rooms.user_num+=1;
    				await roomModel.where({id:rooms.id}).update(rooms);//将人数增加1
    				return rooms;
    			}
    		}
    		go_to_fast().then(emit_root_room);
    		//emit_root_room({id:1});
    	}else if(userInfo.type[0] == "my"){
    		//自己创建一个房间
    		let password = userInfo.type[1];
    		async function createMyRoom(){
    			return await roomModel.add({start_time:time(),is_valid:1,user_num:1,password:password});
    		}
    		createMyRoom().then(emit_root_room);
    	}else if(userInfo.type[0] == "friend"){
    		//朋友的房间
    		let password = userInfo.type[1];
    		async function findFriendRoom(){
    			return await roomModel.where({password:password}).find();
    		}
    		findFriendRoom().then(emit_root_room);
    	}
    	function emit_root_room(rooms){
    		socket.room_id = 'room|'+rooms.id;
			links[socket.id].room_id = 'room|'+rooms.id;
			socket.join('room|'+rooms.id);
			if(!game[socket.room_id]){
				//创建游戏数据
				game[socket.room_id] = {
					users:[],
					chats:[
						// 	{
						// 	icon: "yes",//yes,warning,
						// 	color: "#16a846",//红色#ee191d   #007af8 蓝色  #16a846绿色
						// 	name: "小A",
						// 	content: " "+"刚刚加入了",
						// 	type: false
						// },
						
					],
					draw_users:[],
					no_draw_users:[],
					progress:100,
					progress_cut:0.1,
					canvas:[],
					status:0,
					answer:""
				};
			}

			//添加到房间列表中
			let u = {
				nick_name:userInfo.nick_name,
				head_img:userInfo.head_img,
				num:0,//得分
				id:userInfo.id,
				socket_id:socket.id,
				room_id:socket.room_id,
				openid:userInfo.openid,
				is_fit:false,
				is_draw:false
			};
			if(!getOneUser(game[socket.room_id].users,u)){
				game[socket.room_id].users.push(u);
				game[socket.room_id].no_draw_users.push(u);
				socket.userInfo = u;
			}
			
			socket.emit("afterLogin",game[socket.room_id]);

			//通知有人加入了
			socket.broadcast.to(socket.room_id).emit("someOneJoin",u);
			//创建读秒,返回进度条与status
			if(!clock[socket.room_id]){
				clock[socket.room_id] = setInterval(()=>{
					//判断游戏是否可以开始
					if(game[socket.room_id].users.length > 1 && game[socket.room_id].status == 0){
						//大于2个玩家,并且游戏没有开始时,则游戏开始
						game[socket.room_id].status = 1;
						//选择一个人来画
						check_drawer(socket.room_id);
						//找到一个答案
						let answer = getAnswer();
						game[socket.room_id].progress_cut = 1;
						game[socket.room_id].answer = answer;
						//通知该回答问题的人,准备选取问题
						links[game[socket.room_id].draw_users[(game[socket.room_id].draw_users.length-1)].socket_id].emit("youTurn",{answer:answer});
						//通知其他人,该人正在选择题目
						links[game[socket.room_id].draw_users[(game[socket.room_id].draw_users.length-1)].socket_id].broadcast.to(socket.room_id).emit("ortherTurn",{nick_name:game[socket.room_id].draw_users[(game[socket.room_id].draw_users.length-1)].nick_name});
					}
					
					if(game[socket.room_id].status > 0){
						game[socket.room_id].progress -= game[socket.room_id].progress_cut;
					}


					//时间接近为0时
					if(game[socket.room_id].progress < 1){
						if(game[socket.room_id].status == 1){
							//如果状态还是1,则表明用户没有选择  自动改为2 
							game[socket.room_id].status = 2;
							game[socket.room_id].progress = 100;
							game[socket.room_id].progress_cut = 2;

							let index = game[socket.room_id].draw_users.length - 1;
							if(index >= 0){
								//通知所有人 该人选择跳过
								io.to(socket.room_id).emit("skip_game",game[socket.room_id].draw_users[index]);
							}
							
						}else if(game[socket.room_id].status == 2){
							//如果等于2,则重新开始选择一个绘画者
							game[socket.room_id].status = 1;
							game[socket.room_id].progress = 100;
							game[socket.room_id].progress_cut = 1;
							afterAnswer(socket.room_id);
							check_drawer(socket.room_id);
							//找到一个答案
							let answer = getAnswer();
							game[socket.room_id].progress_cut = 1;
							game[socket.room_id].answer = answer;

							//通知该回答问题的人,准备选取问题
							links[game[socket.room_id].draw_users[(game[socket.room_id].draw_users.length-1)].socket_id].emit("youTurn",{answer:answer});
							//通知其他人,该人正在选择题目
							links[game[socket.room_id].draw_users[(game[socket.room_id].draw_users.length-1)].socket_id].broadcast.to(socket.room_id).emit("ortherTurn",{nick_name:game[socket.room_id].draw_users[(game[socket.room_id].draw_users.length-1)].nick_name});
						}else if(game[socket.room_id].status == 3){
							//时间到了,没有人能答的上来
							game[socket.room_id].status = 2;
							game[socket.room_id].progress = 100;
							game[socket.room_id].progress_cut = 1;
							game[socket.room_id].canvas = [];
							//发消息告诉大家答案
							//所有人的信息归0
							afterAnswer(socket.room_id);
							io.to(socket.room_id).emit("say_answer",{type:"noall",answer:game[socket.room_id].answer});
							
						}
					}


					//如果用户数变为1 ,强制更改状态为0
					if(game[socket.room_id].users.length <= 1){
						if(game[socket.room_id].status > 0){
							//如果是从其他状态转变过来则发送消息   //就剩你一个人了
							links[game[socket.room_id].users[0].socket_id].emit("alone",{});
						}
						game[socket.room_id].progress = 100;
						game[socket.room_id].status = 0;
					}
					let data = {
						progress:game[socket.room_id].progress,
						status:game[socket.room_id].status
					};
					io.to(socket.room_id).emit("status",data);
				},100);
			}
			
    	}
	});
	
	//有人点击跳过
	socket.on("skip",(msg)=>{
		game[socket.room_id].status = 2;
		game[socket.room_id].progress = 100;
		game[socket.room_id].progress_cut = 1;
		for(let i =0;i<game[socket.room_id].users.length;i++){
			game[socket.room_id].users[i].is_draw = false;
		}
		socket.broadcast.to(socket.room_id).emit("skip_game",socket.userInfo);
	});

	//有人点击确定
	socket.on("ok",(msg)=>{
		game[socket.room_id].status = 3;
		game[socket.room_id].progress = 100;
		game[socket.room_id].progress_cut = 0.1;

		//游戏开始
		socket.broadcast.to(socket.room_id).emit("game_start");
	});


	//有人回答
	socket.on("answer",(msg)=>{
		//检测是否是汉字
		let re = /^[\u4e00-\u9fa5]+$/;
		if(!re.test(msg)){
			console.log(msg+",不是汉字");
			return false;
		}

		//判断是否与答案一样
		if(game[socket.room_id].answer == msg){
			socket.emit("afterAnswer",{type:1,userInfo:socket.userInfo,answer:msg});//给自己发
			//给别人发
			socket.broadcast.to(socket.room_id).emit("afterAnswer_other",{type:1,userInfo:socket.userInfo,answer:msg});//给别人发   通知加分

			//如果回答对了,则标记自己已经回答  并且加分
			//计算该用户要加多少分
			createOneMsg(socket.room_id,"success",socket.userInfo.nick_name,"答对了",false);//创建消息
			let u_index = null;
			let draw_index = null;
			let fit_num = 1;
			for(let i=0;i<game[socket.room_id].users.length;i++){
				if(game[socket.room_id].users.is_fit){
					fit_num += 1;
				}
				if(game[socket.room_id].users[i].openid == socket.userInfo.openid){
					u_index = i;
				}
				if(game[socket.room_id].users[i].is_draw){
					draw_index = i;
				}
			}
			let up_num = 11 - fit_num;//需要加的分数
			game[socket.room_id].users[u_index].num += up_num;//给这个人加分
			game[socket.room_id].users[u_index].is_fit = true;
			//给绘画的人加分
			game[socket.room_id].users[draw_index].num += 2;
			//待做: 加分之后提示!!!<><><>
			//判断是否全部答对
			if(fit_num == (game[socket.room_id].users.length-1)){
				//全部都答对了
				game[socket.room_id].status = 2;
				game[socket.room_id].progress = 100;
				game[socket.room_id].progress_cut = 1;
				game[socket.room_id].canvas = [];
				//发消息告诉大家答案
				//所有人的信息归0
				game[socket.room_id].users[draw_index].num += 10;
				io.to(socket.room_id).emit("say_answer",{type:"all",answer:game[socket.room_id].answer});
				io.to(socket.room_id).emit("addCore",{type:0,num:12,userInfo:game[socket.room_id].users[draw_index]});
				afterAnswer(socket.room_id);
			}else{
				io.to(socket.room_id).emit("addCore",{type:0,num:2,userInfo:game[socket.room_id].users[draw_index]});
			}
			
			//给回答的人加分
			io.to(socket.room_id).emit("addCore",{type:0,num:up_num,userInfo:socket.userInfo});
		}else{
			socket.emit("afterAnswer",{type:0,userInfo:socket.userInfo,answer:msg});//给自己发
			createOneMsg(socket.room_id,"warning",socket.userInfo.nick_name,msg,true);//创建消息
			//给别人发
			socket.broadcast.to(socket.room_id).emit("afterAnswer_other",{type:0,userInfo:socket.userInfo,answer:msg});//给别人发
		}
	});

	//有人画画
	socket.on("someOneDraw",function(data){
		//存储动作
		if(data.type != "clean"){
			game[socket.room_id].canvas.push(data);
		}else{
			game[socket.room_id].canvas = [];
		}
		//转发到其他人
		io.to(socket.room_id).emit("otherDraw",data);
	});


	//断开连接
	socket.on('disconnect', function () {
		let roomModel = new room(mysql_config);
		//判断是否在房间中
		if(socket.room_id){
			let rid = socket.room_id.split("|")[1];
			async function leaveFromRoom(){
				let rooms = await roomModel.where({id:rid}).find();
				if(rooms.user_num == 1){
					await roomModel.where({id:rid}).update({end_time:time(),is_valid:0,user_num:0});
				}else if(rooms.user_num > 1){
					rooms.user_num -= 1;
					await roomModel.where({id:rid}).update(rooms);

					//将users 减少
					for(let i=0;i<game[socket.room_id].users.length;i++){
						if(game[socket.room_id].users[i].openid == socket.userInfo.openid){
							game[socket.room_id].users.splice(i,1);
						}
					}
					//将draw_users减少
					for(let i=0;i<game[socket.room_id].draw_users.length;i++){
						if(game[socket.room_id].draw_users[i].openid == socket.userInfo.openid){
							game[socket.room_id].draw_users.splice(i,1);
						}
					}
					//将no_draw_users减少
					for(let i=0;i<game[socket.room_id].no_draw_users.length;i++){
						if(game[socket.room_id].no_draw_users[i].openid == socket.userInfo.openid){
							game[socket.room_id].no_draw_users.splice(i,1);
						}
					}

					//判断是否没有人了
					if(game[socket.room_id].users.length == 1){
						game[socket.room_id].progress = 100;
						game[socket.room_id].status = 0;
					}
					//一个人都没有了
					if(game[socket.room_id].users == 0){
						delete game[socket.room_id];
						delete clock[socket.room_id];
					}
				}
			}
			leaveFromRoom().then(()=>{
				//通知其他人
				socket.broadcast.to('room|'+rid).emit("someOneLeave",socket.userInfo);
				console.log(socket.userInfo.nick_name+" 离开了"+rid+"号房间");
			});
		}
		//删除links中的对象
		delete links[socket.id];
	});
});


http.listen(process.argv[2], function(){
  	console.log('listening on '+process.argv[2]);
});


function check_drawer(room_id){
	//判断用户数是否为1
	if(game[room_id].users.length >= 2){
		//判断没有绘画的人是否还有
		if(game[room_id].no_draw_users.length  == 0){
			//将draw_users 全部放到no_draw_users中
			game[room_id].no_draw_users = game[room_id].draw_users;
			game[room_id].draw_users = [];
		}
		let this_drawr = game[room_id].no_draw_users.shift();
		this_drawr.is_draw = true;
		game[room_id].draw_users.push(this_drawr);
	}
}

function time(){
	return parseInt(new Date().getTime()/1000);
}
function isEmpty(e) {  
    var t;  
    for (t in e)  
        return !1;  
    return !0  
}  


function getOneUser(users,user){
	let r = false;
	for(let i=0;i<users.length;i++){
		if(user.openid == users[i].openid){
			r = true;
		}
	}
	return r;
}

function getAnswer(){
	let arr = ["电脑","耳机","收音机","洗衣机","手机"];
	let n = Math.floor(Math.random() * arr.length + 1)-1;  
	return arr[n];
}

//用户信息归零
function afterAnswer(room_id){
	for(let i=0;i<game[room_id].users.length;i++){
		game[room_id].users[i].is_fit = false;
		game[room_id].users[i].is_draw = false;
	}
}

//添加一个消息
function createOneMsg(room_id,type,first,last,t){
	let icon = "warning";
	let color = "#bbbbbb";
	if(type == "info"){
		icon = "warning";
		color = "#007af8";
	}else if(type == "success"){
		icon = "yes";
		color = "#16a846";
	}else if(type == "danger"){
		icon = "no";
		color = "#ee191d";
	}
	let data = {
		icon: icon,//yes,warning,
		color: color,//红色#ee191d   #007af8 蓝色  #16a846绿色
		name: first,
		content: " "+last,
		type: (t?true:false)
	};
	game[room_id].chats.push(data);
	return data;
}